"""
=================================================
@Author: Zenon
@Date: 2025-05-21
@Description：时序异常检测系统主窗口
==================================================
"""
import configparser
import sqlite3

from PySide6.QtCore import Qt
from PySide6.QtGui import QFont
from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QStackedWidget)
from loguru import logger

from ui.detection_page import DetectionPage
from ui.history_page import HistoryPage
from ui.home_page import HomePage
from ui.model_page import ModelPage


class TSADSystem(QWidget):
    """时序异常检测系统主窗口"""
    def __init__(self):
        super().__init__()

        # 模型参数映射（模型名称 -> 参数列表）
        self.model_params_map = {
            "TranAD": ["窗口大小", "预测步长", "隐藏维度", "注意力头数", "层数", "学习率"],
            "InterFusion": ["嵌入维度", "编码器层数", "解码器层数", "融合因子", "阈值", "批量大小"],
        }

        # 初始化空的检测历史数据
        self.detection_history_data = []

        # 读取配置文件
        self.config = configparser.ConfigParser()
        self.config.read('config/config.ini', encoding='utf-8')
        
        # 连接SQLite数据库
        db_path = self.config.get('DATABASE', 'db_path')
        self.conn = sqlite3.connect(db_path)
        self.cursor = self.conn.cursor()
        self.create_models_table()

        # 设置窗口标题和大小
        self.setWindowTitle("TSAD系统")
        self.setFixedSize(800, 600)

        # 统一字体设置
        self.font = QFont("Arial", 12)

        # 创建页面
        self.setup_ui()
        
        # 初始化日志
        logger.info("TSAD系统已启动")
        
    def setup_ui(self):
        """设置UI界面"""
        # 左侧导航栏布局
        left_layout = QVBoxLayout()
        left_layout.setAlignment(Qt.AlignTop)

        # 导航按钮
        self.home_button = self.create_nav_button("首页", 0)
        self.model_button = self.create_nav_button("模型", 1)
        self.anomaly_detection_button = self.create_nav_button("异常检测", 2)
        self.detection_history_button = self.create_nav_button("检测历史", 3)

        left_layout.addWidget(self.home_button)
        left_layout.addWidget(self.model_button)
        left_layout.addWidget(self.anomaly_detection_button)
        left_layout.addWidget(self.detection_history_button)

        # 创建 QStackedWidget 来管理不同的页面
        self.stacked_widget = QStackedWidget()
        
        # 创建各个页面
        self.home_page = HomePage(self)
        self.model_page = ModelPage(self)
        self.detection_page = DetectionPage(self)
        self.history_page = HistoryPage(self)
        
        # 添加页面到堆栈窗口
        self.stacked_widget.addWidget(self.home_page)
        self.stacked_widget.addWidget(self.model_page)
        self.stacked_widget.addWidget(self.detection_page)
        self.stacked_widget.addWidget(self.history_page)

        # 整体布局
        main_layout = QHBoxLayout()
        main_layout.addLayout(left_layout)
        main_layout.addWidget(self.stacked_widget)
        self.setLayout(main_layout)
        
        # 默认显示首页
        self.show_page(0)
        
    def create_nav_button(self, text, page_index):
        """创建导航按钮"""
        from PySide6.QtWidgets import QPushButton
        
        button = QPushButton(text)
        button.setFont(self.font)
        button.clicked.connect(lambda: self.show_page(page_index))
        return button
        
    def show_page(self, index):
        """显示指定页面并更新按钮样式"""
        self.stacked_widget.setCurrentIndex(index)
        # 重置所有按钮样式
        self.home_button.setStyleSheet("")
        self.model_button.setStyleSheet("")
        self.anomaly_detection_button.setStyleSheet("")
        self.detection_history_button.setStyleSheet("")
        # 设置当前选中按钮的样式
        if index == 0:
            self.home_button.setStyleSheet("background-color: #007acc; color: white;")
        elif index == 1:
            self.model_button.setStyleSheet("background-color: #007acc; color: white;")
        elif index == 2:
            self.anomaly_detection_button.setStyleSheet("background-color: #007acc; color: white;")
        elif index == 3:
            self.detection_history_button.setStyleSheet("background-color: #007acc; color: white;")
            
    def create_models_table(self):
        """创建模型表"""
        try:
            self.cursor.execute('''
                CREATE TABLE IF NOT EXISTS models (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    model_name TEXT,
                    create_time TEXT,
                    description TEXT
                )
            ''')
            self.conn.commit()
            logger.info("模型表已创建/验证")
        except Exception as e:
            logger.error(f"创建模型表失败: {str(e)}")